//
//  AppDelegate.swift
//  Kkmh-Swift
//
//  Created by tenltrs on 2018/10/25.
//  Copyright © 2018 Tenltrs. All rights reserved.
//

import UIKit

let logger = XCGLogger.default

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {

    var window: UIWindow?
    
    var reachability : Reachability!

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        self.window?.backgroundColor=UIColor.NavColor

        
        if #available(iOS 11.0, *) {
            //防止tableView界面乱跑
            UITableView.appearance().estimatedRowHeight = 0;
            UITableView.appearance().estimatedSectionFooterHeight = 0;
            UITableView.appearance().estimatedSectionHeaderHeight = 0;
        } else {
            // Fallback on earlier versions
        }
        
        //初始化缓存
        if UserDefaults.standard.value(forKey: GenderKey) == nil {
            UserDefaults.standard.set(1, forKey: GenderKey) //默认男生版
        }

        //初始化日志打印管理
        self.initLog()
        
        //添加网络监听
        self.setNetWorkMonitoring()
        
        //设置键盘工具
        self.setKeyboardManager()
        
        //初始化友盟 配置
//        UMConfigure.initWithAppkey(UMAppKey, channel: nil)
        
//        let entity = UMessageRegisterEntity()
//        entity.types = Int(UMessageAuthorizationOptions.badge.rawValue|UMessageAuthorizationOptions.sound.rawValue|UMessageAuthorizationOptions.alert.rawValue)
//        if #available(iOS 10.0, *) {
//            UNUserNotificationCenter.current().delegate=self
//        } else {
//            // Fallback on earlier versions
//        }
//        UMessage.registerForRemoteNotifications(launchOptions: launchOptions, entity: entity) { (granted, error) in
//
//        }
//        
//        UMessage.getTags { (responseTags, remain, error) in
//            
//            logger.info()
//        }
//        
//        UMessage.addTags("59") { (responseObject, remain, error) in
//            
//            logger.info()
//        }
        
        self.window?.rootViewController=RootViewController()
        
        return true
    }
    
 
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        
        UMessage.registerDeviceToken(deviceToken)
        
        let device = NSData(data: deviceToken)
        
        let deviceId = device.description.replacingOccurrences(of:"<", with:"").replacingOccurrences(of:">", with:"").replacingOccurrences(of:" ", with:"")
        
        logger.info("deviceToken ===== \(deviceId)")
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ssss"), object: deviceId)
    }
    
    
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
        let userInfo = notification.request.content.userInfo
        if(notification.request.trigger is UNPushNotificationTrigger){
            
            UMessage.setAutoAlert(false)
            
            UMessage.didReceiveRemoteNotification(userInfo)
            
            let alertVc = UIAlertController.init(title: "来推送了", message: nil, preferredStyle: .alert)
            
            let action = UIAlertAction.init(title: "确定", style: .cancel) { (action) in
                
                
            }
            alertVc.addAction(action)
            
            let vc : BaseViewController? = CURRENT_VC()
            vc?.present(alertVc, animated: true, completion: nil)
            
        }else{
            
        }
        
    }
    
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        
        let userInfo = response.notification.request.content.userInfo
        if(response.notification.request.trigger is UNPushNotificationTrigger){
            
            UMessage.didReceiveRemoteNotification(userInfo)
            UMessage.sendClickReport(forRemoteNotification: userInfo)
            
            CommUtls.gcd_perform(after: 2) {
                let alertVc = UIAlertController.init(title: "后台来推送了", message: nil, preferredStyle: .alert)
                
                let action = UIAlertAction.init(title: "确定", style: .cancel) { (action) in
                    
                    
                }
                alertVc.addAction(action)
                
                let vc : BaseViewController? = CURRENT_VC()
                vc?.present(alertVc, animated: true, completion: nil)
            }
            
        }else{
            
        }
        
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

